import os.path

import mirai
from mirai import MessageEvent, FriendMessage, GroupMessage, TempMessage, Image


# TODO 可以考虑再封装一层 处理引用回复等操作
async def send_message(bot, event: MessageEvent, message_chain: mirai.MessageChain):
    if isinstance(event, FriendMessage):
        await bot.send_friend_message(event.sender.id, message_chain)
    if isinstance(event, GroupMessage):
        await bot.send_group_message(event.sender.group.id, message_chain)
    if isinstance(event, TempMessage):
        await bot.send_temp_message(event.sender.id, message_chain)


def search_image_storage(image_id: str):
    return os.path.isfile(image_id)


async def image_persistence(message_chain: mirai.MessageChain):
    # 将消息链中的图片持久化到本地, 以便于接下来的处理

    new_message_chain = mirai.MessageChain()

    for unit in message_chain:
        if isinstance(unit, Image):
            file_name = f'./image_storage/{unit.image_id.replace("{", "").replace("}", "")}'
            if not search_image_storage(file_name):
                try:
                    await unit.download(filename=file_name, determine_type=False)
                except Exception:
                    raise
            if search_image_storage(file_name):
                unit = Image(path=file_name)
        new_message_chain.append(unit)

    return new_message_chain
